package com.eu.ebpm.engine.cmd;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.eu.ebpm.engine.entity.deploy.Mission;
import com.eu.ebpm.engine.entity.runtime.TaskIdentity;
import com.eu.ebpm.engine.exception.ErrorCode;
import com.eu.ebpm.engine.exception.WorkFlowException;
import com.eu.ebpm.engine.repository.TaskIdentityRepository;
import com.eu.ebpm.engine.service.Task;
import org.springframework.util.StringUtils;

@Component
public class TaskIdentitySupport {

	@Autowired
	private TaskIdentityRepository taskIdentityRepository;

	public void insertTaskCandidate(Mission mission, Task task) {

		if (!StringUtils.isEmpty(task.getAssignee())) {
			return;
		}

		if (mission.existsCandidate()) {
			throw new WorkFlowException(ErrorCode.RU_NOTEXISTS_CANDIDATE);
		}

		int maxSize = 1;
		
		String[] users = null;
		if (!StringUtils.isEmpty(mission.getUser())) {
			if (mission.getUser().indexOf(",") > 0) {
				users = mission.getUser().split(",");
				maxSize = users.length;
			} else {
				users = new String[] { mission.getUser() };
			}
		}

		String[] roles = null;
		if (!StringUtils.isEmpty(mission.getRoler())) {
			if (mission.getRoler().indexOf(",") > 0) {
				roles = mission.getRoler().split(",");
				if(roles.length > maxSize) {
					maxSize = roles.length;
				}
			} else {
				roles = new String[] { mission.getRoler() };
			}
		}

		String[] orgs = null;
		if (!StringUtils.isEmpty(mission.getOrg())) {
			if (mission.getOrg().indexOf(",") > 0) {
				orgs = mission.getOrg().split(",");
				if(orgs.length > maxSize) {
					maxSize = orgs.length;
				}
			} else {
				orgs = new String[] { mission.getOrg() };
			}
		}

		for (int i = 0; i < maxSize; i++) {

			TaskIdentity ti = new TaskIdentity();
			
			ti.setTaskId(task.getId());

			if (users != null && users.length > i) {
				ti.setUser(users[i]);
			}

			if (roles != null && roles.length > i) {
				ti.setRoler(roles[i]);
			}

			if (orgs != null && orgs.length > i) {
				ti.setOrg(orgs[i]);
			}

			taskIdentityRepository.insert(ti);
		}

	}

}
